const User = require('./../../util/user') //用户 
const wxConfig = require('./../../util/wx_x_config')
const card = require('./../../util/card') //会员卡表
const subject = require('./../../util/subject') //课程表
const request = require('request')
let user = async(router, opt) => {
	// 获取个人信息
	router.post('/getUserInfo', async (ctx, next) => {
	  let {body} = ctx.request
	  var res = await opt.find(User, {
	      'openid': body.openid
	    })

	  //第一次获取信息的时候查看是数据库是否又用户信息 没有用户信息的话注册一份
	  if (!res) {
	    res = await opt.insert(User, {
	      openid: ctx.request.body.openid
	    }, (res, err) => {
	      if (err) return err
	      return res
	    })
	  }

	  // 如果说是新用户的的直接返回新对象
	  if (typeof res == 'string' && res == 'success') {
	        res = {
	          "clockIn" : [ ],
	          "subject" : [ ],
	          "cardList" : [ ]
	        }
	  }
	  let sub = await opt.findAll(subject, {openId: body.openid, status: 100})
	  let cards = await opt.findAll(card, {openId: body.openid, status: 100})
	  // console.log('sub', sub, body.openid);
	  res.subject = sub || []
	  res.cardList = cards || []
	  ctx.body = {
	        res: 'ok',
	        status: 200,
	        data: res
	      }

	})


	// 微信服务区获取个人信息
	router.post('/getId', async(ctx, next) => {
	  
	  // let pc = new WXBizDataCrypt(wxConfig.AppID, wxConfig.Secret);

	  var tempData = ctx.request.body;
	  
	  // https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
	  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxConfig.AppID}&secret=${wxConfig.Secret}&js_code=${tempData.js_code}&grant_type=authorization_code`;
	  var data = {
	    appid: wxConfig.AppID,
	    secret: wxConfig.Secret,
	    js_code: ctx.request.body.code,
	    grant_type: 'authorization_code'
	  }
	  
	  return new Promise(function(resolve, reject) {
	    request({
	      url: url,
	      method: 'get',
	      dataType:"JSON",
	    },
	    (err, res, body) => {
	      if (err) ctx.body = {'res': 'error'};
	      else {
	        var dataJson = JSON.parse(body)
	        ctx.body = dataJson;
	      }
	      resolve(next())
	      
	    })
	  })
	})


	// 设置个人信息
	router.post('/setUserInfo', async(ctx, next) => {
	  var user = {

	    "cardList": [{
	      "type": "vip",
	      "name": "成人季度卡",
	      "ntatorium": "599552106b4944bbc2039e50",
	      "id": "123456",
	      "time": {
	        "start": 1503306910600,
	        "indate": 1513847710600
	      }

	    }, {
	      "type": "number",
	      "name": "30次卡",
	      "ntatorium": "599552106b4944bbc2039e50",
	      "id": "123451",
	      "number": 30

	    }]
	  }
	  var res = await User.update({
	      "openid": 'oIWMZ0e2vuDpM9FPQ7R4fJQ8hVHw'
	    }, (res, err) => {
	      if (err) return err
	      return res
	    })
	    // console.log(res, 'setUserInfo')
	    // var res = await opt.findById(Natatorium,ctx.request.body.id)
	  ctx.body = {
	    res: 'ok',
	    status: 200
	  }

	})

	//注册信息
	router.post('/user/register', async (ctx, next) => {
		const { body } = ctx.request;
	    try {
	      if (!body.username || !body.password) {
	        ctx.status = 400;
	        ctx.body = {
	          error: `expected an object with username, password but got: ${body}`,
	        }
	        return;
	      }
	      // body.password = await bcrypt.hash(body.password, 5)
	      let user = await User.find({ username: body.username });
	      
	      ctx.body = body;

	      // if (!user.length) {

	      //   const newUser = new User(body);
	      //   user = await newUser.save();
	      //   ctx.status = 200;
	      //   ctx.body = {
	      //     message: '注册成功',
	      //     user,
	      //   }
	      // } else {
	      //   ctx.status = 406;
	      //   ctx.body = {
	      //     message: '用户名已经存在',
	      //   }
	      // }
	    } catch (error) {
	      ctx.throw(500)
	    }
		
	})
}

module.exports = user